#!/bin/bash -x

kata_coco_top_dir="$HOME/workspace/CoCo"

operator_repo_url="https://gitee.com/hanliyang-kata-coco/operator.git"
operator_repo_branch="0.12.0-hygon-arch-sig"
operator_repo_dir="${kata_coco_top_dir}/operator"

operator_controller_dir="${operator_repo_dir}/config/release"
operator_ccruntime_dir="${operator_repo_dir}/config/samples/ccruntime/default"
operator_ccruntime_kustomize="${operator_ccruntime_dir}/kustomization.yaml"
operator_ccruntime_base_yaml="${operator_ccruntime_dir}/../base/ccruntime.yaml"
operator_k8s_namespace="confidential-containers-system"
operator_controller_k8s_podname_prefix="cc-operator-controller-manager"
operator_ccruntime_daemon_install_k8s_podname_prefix="cc-operator-daemon-install"
operator_ccruntime_kata_deploy_uri=""

usage () {
  set +x
  echo -e "\033[31m
Usage: $0 [-h] [-p <kata-deploy-registry>]

       -h,--help    Display this help message
       -p,--payload The payload kata-deploy image (deploy kata & coco components onto the k8s worker node).
                    Default is docker.io/robertsonhan/kata-deploy-csv:3.11.0
\033[0m"
  set -x
}

params=$(getopt -o hp: --long help,payload: -- "$@")
if [ $? -ne 0 ]; then
  echo "[Error] cannot parse parameters"
  exit 1
fi

eval set -- "$params"

while true; do
  case "$1" in
  -h|--help)
    usage
    exit 0
    ;;
  -p|--payload)
    operator_ccruntime_kata_deploy_uri="$2"
    shift 2
    ;;
  --)
    shift
    break
    ;;
  *)
    usage
    exit 1
    ;;
  esac
done

if [ ! -e ${operator_repo_dir} ]; then
  command git help > /dev/null
  if [ $? -ne 0 ]; then
    sudo yum install -y git
  fi

  mkdir -p $(dirname ${operator_repo_dir}) || true

  git clone ${operator_repo_url} \
    -b ${operator_repo_branch} \
    ${operator_repo_dir}
fi

revoke_operator_controller () {
  echo "[Revoke operator controller]"
  kubectl delete -k ${operator_controller_dir}
}

revoke_operator_ccruntime () {
  echo "[Revoke operator ccruntime]"
  kubectl delete -k ${operator_ccruntime_dir}
  sudo rm -rf /opt/kata || true
}

init_operator () {
  echo "[Init operator]"
  revoke_operator_ccruntime
  revoke_operator_controller

  echo "[Update operator ccruntime kustomize]"
  local proxy=""

  pushd ${operator_ccruntime_dir}
  git checkout .

  echo "[  Set kata-agent's proxy (if you don't do this, you may need add containerd annotations to the pod yaml)]"
  proxy="${https_proxy}"
  if [ "X${proxy}" = "X" ]; then
    proxy="${HTTPS_PROXY}"
  fi
  if [ "X${proxy}" != "X" ]; then
    sed -i "/# - name: \"AGENT_HTTPS_PROXY\"/i\        - name: \"AGENT_HTTPS_PROXY\"" \
      ${operator_ccruntime_kustomize}
    sed -i "/# - name: \"AGENT_HTTPS_PROXY\"/i\          value: \"${proxy}\"" \
      ${operator_ccruntime_kustomize}
  fi

  proxy="${no_proxy}"
  if [ "X${proxy}" = "X" ]; then
    proxy="${NO_PROXY}"
  fi
  if [ "X${proxy}" != "X" ]; then
    sed -i "/# - name: \"AGENT_NO_PROXY\"/i\        - name: \"AGENT_NO_PROXY\"" \
      ${operator_ccruntime_kustomize}
    sed -i "/# - name: \"AGENT_NO_PROXY\"/i\          value: \"${proxy}\"" \
      ${operator_ccruntime_kustomize}
  fi

  echo "[  Set kata-deploy registry uri]"
  if [ "X${operator_ccruntime_kata_deploy_uri}" != "X" ]; then
    git checkout ${operator_ccruntime_base_yaml}
    sed -i "/kata-deploy-csv/ s/payloadImage: \(.*\)$/payloadImage: ${operator_ccruntime_kata_deploy_uri//\//\\\/}/" ${operator_ccruntime_base_yaml}
    kustomize edit set image \
      quay.io/kata-containers/kata-deploy=${operator_ccruntime_kata_deploy_uri}
  fi
  popd # ${operator_ccruntime_dir}
}

init_operator

run_operator_controller () {
  echo "[Run operator controller]"
  kubectl apply -k ${operator_controller_dir}

  wait_max_secs=300
  wait_cnt=0
  while [ $(kubectl get pods -n ${operator_k8s_namespace} | \
    grep ${operator_controller_k8s_podname_prefix} | \
    grep -c "\<Running\>") -eq 0 ]; do
    sleep 1
    let wait_cnt++
    if [ ${wait_cnt} -gt ${wait_max_secs} ]; then
      revoke_operator_controller
      echo "Run operator controller [FAIL], you need debug the root cause"
      exit 1
    fi
  done

  # show operator controller status
  sleep 10
  kubectl get pods -n ${operator_k8s_namespace}
  kubectl get crd
}

run_operator_controller

run_operator_ccruntime () {
  echo "[Run operator ccruntime]"
  kubectl apply -k ${operator_ccruntime_dir}

  wait_max_secs=600
  wait_cnt=0
  while [ $(kubectl get pods -n ${operator_k8s_namespace} | \
    grep ${operator_ccruntime_daemon_install_k8s_podname_prefix} | \
    grep -c "\<Running\>") -eq 0 ]; do
    sleep 1
    let wait_cnt++
    if [ ${wait_cnt} -gt ${wait_max_secs} ]; then
      revoke_operator_ccruntime
      revoke_operator_controller
      echo "Run operator ccruntime [FAIL], you need debug the root cause"
      exit 1
    fi
  done

  # show operator ccruntime status
  sleep 10
  kubectl get pods -n ${operator_k8s_namespace}
  echo "[  check kata & coco runtimeclass]"
  kubectl get runtimeclass
  echo "[  check nydus-snapshotter]"
  ps -elf | grep nydus
}

run_operator_ccruntime
